﻿using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class OPCDA
    {
        public static void OPCDAComm()
        {
            //Server->Group  Group->Items->Item
            OPCServer server = new OPCServer();
            server.Connect("Kepware.KEPServerEX.V6");
            //
            RecurBrowse(server.CreateBrowser());
            //读写
            OPCGroup group = server.OPCGroups.Add();
            var item1 = group.OPCItems.AddItem("通道 1.设备 1.标记 1", 1);
            var item2 = group.OPCItems.AddItem("通道 1.设备 1.标记 2", 2);
            var item3 = group.OPCItems.AddItem("通道 1.设备 1.标记 3", 3);

            Array serverHandles = new int[] { 0, item1.ServerHandle, item2.ServerHandle, item3.ServerHandle };
            Array values = new object[] { 0 };
            Array errors = new object[] { 0 };

            //读取
            group.SyncRead((short)OPCDataSource.OPCDevice, group.OPCItems.Count, ref serverHandles, out values, out errors, out object q, out object t);
            //写入
            group.SyncWrite(group.OPCItems.Count, ref serverHandles, ref values, out errors);
            //关闭
            server.Disconnect();
        }

        /// <summary>
        /// 展开树枝和叶子
        /// </summary>
        /// <param name="oPCBrowser">opc浏览器</param>
        public static void RecurBrowse(OPCBrowser oPCBrowser)
        {
            //展开分支
            oPCBrowser.ShowBranches();
            //展开叶子
            oPCBrowser.ShowLeafs(true);
            foreach (object turn in oPCBrowser)
            {
                Console.WriteLine(turn.ToString());
            }
        }
    }
}
